package com.hs.myshell.edit;

import java.awt.Color;
import java.awt.Frame;
import java.awt.TextField;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.nio.CharBuffer;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.swt.SWT;
import org.eclipse.swt.awt.SWT_AWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.EditorPart;

import com.cyclone.terminal.emulator.datascope.SimpleDataScopeDialog;
import com.google.common.base.Ascii;
import com.grahamedgecombe.jterminal.JTerminal;
import com.grahamedgecombe.jterminal.vt100.Vt100TerminalModel;
import com.hs.myshell.demo.swt.CanvasSample;
import com.hs.myshell.demo.swt.MyCursor;
import com.hs.myshell.ssh.ISSHClient;
import com.hs.myshell.ssh.SSHClient;

import net.schmizz.sshj.common.IOUtils;


/**
 * https://eliyar.biz/ssh-highlight/
 * 目录前后的是 黑体加粗的高亮控制符
 */
public class TerminalEditor extends EditorPart {
	
	private ISSHClient sshClient;
	private MyVT100 shell;

	public static String ID = "com.hs.myshell.edit.terminaleditor";
	
	/**
	 * ��Ļ
	 */
	private Text screen;
	/**
	 * ����������
	 */
	private Text commandInput;
	private InputStream originInputStream;
	private OutputStream originOutputStream;
	private PipedInputStream inputStream;
	private InputStreamReader reader;
	private volatile Job readerJob;
	private StringBuffer commandBuffer = new StringBuffer();
	private StringBuffer allBuffer = new StringBuffer();
	
	public TerminalEditor() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void doSave(IProgressMonitor monitor) {
		// TODO Auto-generated method stub

	}

	@Override
	public void doSaveAs() {
		// TODO Auto-generated method stub

	}

	@Override
	public void init(IEditorSite site, IEditorInput input) throws PartInitException {
		// TODO Auto-generated method stub
		this.setSite(site);
		this.setInput(input);
	}

	@Override
	public boolean isDirty() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean isSaveAsAllowed() {
		// TODO Auto-generated method stub
		return false;
	}
	
	

	@Override
	public void dispose() {
		System.out.println("销毁定时器...");
		if (myRepaintTimer != null) {
			myRepaintTimer.stop();
		}
	}



	private JPanel swingPanel;
	
	JTerminal jterminal;
	
	
	Timer myRepaintTimer = null;
	protected int cursorFlag;
	
	/**
	 https://www.eclipse.org/swt/snippets/
	 
	 
	    gc.fillRectangle(xx, y, this.fStyleMap.getFontWidth(), this.fStyleMap.getFontHeight());
	    if (c != ' ' && c != 0) {
	        gc.drawString(String.valueOf(c), this.fStyleMap.getCharOffset(c) + xx, y, true);
	    }
	    先画一个矩形，再填一个字符
	 */
	Canvas canvas;
	@Override
	public void createPartControl(Composite parent) {
		//初始输出
		commandBuffer.append("welcome");
//		this.shell = new MyVT100(parent,200,200,300);
//		shell.setDataScope(new SimpleDataScopeDialog(parent));
//		Canvas canvas = new Canvas(parent, SWT.TOP);
		canvas = new Canvas(parent, SWT.H_SCROLL|SWT.V_SCROLL);
//		https://www.sioe.cn/yingyong/yanse-rgb-16/   颜色值      苍白的绿宝石 175,238,238
		org.eclipse.swt.graphics.Color color = new org.eclipse.swt.graphics.Color(new RGB(175,238,238));
		canvas.setBackground(color);
//		swingTerminal(parent);
//		swingDemo(parent);
		
		canvas.addListener(SWT.Paint, new Listener() {
			
			@Override
			public void handleEvent(org.eclipse.swt.widgets.Event event) {
				System.out.println("canvas is Paint");
			}
		});
		canvas.addListener(SWT.Resize, new Listener() {
			
			@Override
			public void handleEvent(Event event) {
				System.out.println("resize");
			}
		});
		canvas.addListener(SWT.V_SCROLL, new Listener() {
			
			@Override
			public void handleEvent(org.eclipse.swt.widgets.Event event) {
				System.out.println("V_SCROLL");
			}
		});
		canvas.addListener(SWT.H_SCROLL, new Listener() {
			
			@Override
			public void handleEvent(org.eclipse.swt.widgets.Event event) {
				System.out.println("H_SCROLL");
			}
		});
		canvas.addKeyListener(new KeyListener() {
			
			@Override
			public void keyReleased(KeyEvent e) {
				char keyCharacter = e.character;
				System.out.println("keyReleased: "+e.keyCode +" keyChar: " + keyCharacter);
				if(keyCharacter == SWT.CR) {
					System.out.println("发送命令。。。 ");
				}
				//把命令放入buffer缓冲池,通过定时任务 redraw的时候,重新绘制Canvas面板
				commandBuffer.append(keyCharacter);
//				sendCommand(String.valueOf(keyCharacter));
			}
			@Override
			public void keyPressed(KeyEvent e) {
//				System.out.println("keyPressed: "+e.keyCode);
//				if(e.character == SWT.CR) {
//					String string = commandBuffer.toString();
////					sendCommand(string);
//					System.out.println("发送命令。。。 " + string);
////					commandBuffer.delete(0,commandBuffer.length());
//				}
			}
		});
		final Point origin = new Point (0, 0);
		final int width = 500;
		
//		ScrollBar hBar = canvas.getHorizontalBar();
//		hBar.addListener (SWT.Selection, new Listener () {
//			
//			@Override
//			public void handleEvent(org.eclipse.swt.widgets.Event event) {
//				 System.out.println("HBar listener");
//	             int hSelection = hBar.getSelection ();
//	             int destX = -hSelection - origin.x;
//	             canvas.scroll (destX, 0, 0, 0, width, 100, true);
//	             origin.x = -hSelection;
//	             System.out.println("HBar listener exit");
//			}
//	     });
		
		int row = 0;
		int col = 0;
		final MyCursor myCursor = new MyCursor();
		final MyCursor bufferMyCursor = new MyCursor();
		myCursor.setCol(col);
		myCursor.setRow(row);
		
		canvas.addPaintListener(new PaintListener(){
			public void paintControl(PaintEvent e){
				//绘制图像
//				e.gc.drawImage(image, 10, 10);
				//绘制椭圆
//				e.gc.drawOval(20, 20, 200, 100);
				//绘制直线
//				e.gc.drawLine(20,10,100,20);
				
//				Font font = new Font(e.display, "Arial", 14, SWT.BOLD | SWT.ITALIC);
				Font font = new Font(e.display, "Consolas", 10, SWT.NONE);
				Point fontSize = e.gc.textExtent("W");
				e.gc.setFont(font);
				//绘制矩形
				
				
				//绘制字符串
//				e.gc.drawString("h", col, 0);
				//这个单位是像素,如果要在Y坐标下移一个的话，要乘以当前字体的高度
				
				//每次重新绘制的时候,把缓冲池的拿过来,然后清空缓冲池,ssh可以慢慢的发,
				//例如 pwd+回车,最后再输入回车的时候,前面预输入的pwd依然有效,ssh协议应该是缓冲了之前的输入字符
				String currentInput = commandBuffer.toString();
				boolean hasNewInput = currentInput.length() != 0;
				if(hasNewInput) {
					//有新的输入
					commandBuffer.delete(0, commandBuffer.length());
					allBuffer.append(currentInput);
				}else {
					//还原之前的 列号 行号,反正都是要 重新绘制
					myCursor.setCol(0);
					myCursor.setRow(0);
				}
				myCursor.setCol(0);
				myCursor.setRow(0);
				
				char[] charArray = allBuffer.toString().toCharArray();
				
				
				for (char c : charArray) {
					if(Ascii.CR == c) {
						System.out.println("CR,回车,把光标移到0坐标");
						myCursor.setCol(0);
						continue;
					}
					if(Ascii.LF == c) {
						int tempRow=(myCursor.getRow() + 1) * fontSize.y;
						myCursor.setRow(tempRow);
						System.out.println("LF,换行,把光标移到Y坐标+1");
						continue;
					}
					e.gc.setBackground(e.display.getSystemColor(SWT.COLOR_WHITE));
					e.gc.setForeground(e.display.getSystemColor(SWT.COLOR_BLACK));
//						e.gc.fillRectangle(col, 0, fontSize.x-5, fontSize.y-5);
					e.gc.drawString(String.valueOf(c), myCursor.getCol(), 0);
					
					myCursor.addColFontSize(fontSize.x);
				}
				/**
				 * 如果有新的输入 把之前的 坐标缓冲起来
				 */
				if (hasNewInput) {
					myCursor.cloneCursor(bufferMyCursor);
				}
				
				//绘制光标
				if (cursorFlag%2==1) {
					e.gc.setBackground(e.display.getSystemColor(SWT.COLOR_BLACK));
				}else {
					e.gc.setBackground(e.display.getSystemColor(SWT.COLOR_WHITE));
				}
				cursorFlag++;
				e.gc.fillRectangle(myCursor.getCol(), myCursor.getRow(), fontSize.x, fontSize.y);
//				Toolkit.getDefaultToolkit().beep();
				
				
				
//				//设置display前景色
//				e.gc.setForeground(e.display.getSystemColor(SWT.COLOR_GREEN));
//				//设置display字体
//				e.gc.setFont(font);
//				//设置display 背景色
//				e.gc.setBackground(e.display.getSystemColor(SWT.COLOR_DARK_GRAY));
//				//再绘制字符串
//				e.gc.drawString("T", 30, 50);
				
				
//				font.dispose();
			}
		});
		
		if (myRepaintTimer != null) {
			myRepaintTimer.stop();
		}
		myRepaintTimer = new Timer(1000,new RePaintTimer(this));
		myRepaintTimer.start();
		
//		initPollingMsgJob();
		
		/*
		 * GC gc = new GC (canvas);
		 * 
		 * Display current = Display.getCurrent(); Font font = new Font(current,
		 * "Arial", 14, SWT.BOLD | SWT.ITALIC); //绘制字符串
		 * gc.drawString("This is a String", 30, 20);
		 * 
		 * //设置display前景色 gc.setForeground(current.getSystemColor(SWT.COLOR_GREEN));
		 * //设置display字体 gc.setFont(font); //设置display 背景色
		 * gc.setBackground(current.getSystemColor(SWT.COLOR_DARK_GRAY)); //再绘制字符串
		 * gc.drawString("This is a String", 30, 50);
		 * 
		 * font.dispose();
		 */
//		initEditor(parent);
	}

	/**
	 * 嵌入swing的终端
	 * @param parent
	 */
	private void swingTerminal(Composite parent) {
		Composite composite = new Composite(parent, SWT.EMBEDDED | SWT.NO_BACKGROUND);
		final Frame frame = SWT_AWT.new_Frame(composite);
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
//				Vt100TerminalModel model = new Vt100TerminalModel(80,25,30);
//				jterminal = new JTerminal(model);
				jterminal = new JTerminal();
				jterminal.getInput().addKeyListener(new java.awt.event.KeyListener() {
					
					@Override
					public void keyTyped(java.awt.event.KeyEvent e) {
						// TODO Auto-generated method stub
						
					}
					
					@Override
					public void keyReleased(java.awt.event.KeyEvent e) {
						
					}
					
					@Override
					public void keyPressed(java.awt.event.KeyEvent e) {
						System.out.println("keyPressed--------------: "+e.getKeyCode());
						if(e.getKeyCode() == 10) {//10 按下的是回车键
							TextField input = jterminal.getInput();
							sendCommand(input.getText());
						}
						
					}
				});
				jterminal.getButton().addActionListener(new ActionListener() {
					
					@Override
					public void actionPerformed(ActionEvent e) {
						TextField input = jterminal.getInput();
						sendCommand(input.getText());
					}
				});
				frame.add(jterminal);
			}
		});
	}
	private void swingDemo(Composite parent) {
		Composite composite = new Composite(parent, SWT.EMBEDDED | SWT.NO_BACKGROUND);
		final Frame frame = SWT_AWT.new_Frame(composite);
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				swingPanel = new JPanel();
				JButton button = new JButton("Swing Button");
				swingPanel.add(button);
				frame.add(swingPanel);
			}
		});
	}

	private void initEditor(Composite parent) {
		Composite top = new Composite(parent, SWT.NONE);
		GridLayout layout = new GridLayout();
		layout.marginWidth = 0;
		layout.marginHeight = 0;
		top.setLayout(layout);
		
		screen = new Text(top, SWT.BORDER|SWT.MULTI|SWT.WRAP);
		screen.setLayoutData(new GridData(GridData.FILL,GridData.FILL,true,true));
		screen.setEditable(true);
		screen.setBackground(screen.getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND));
		screen.setForeground(screen.getDisplay().getSystemColor(SWT.COLOR_INFO_FOREGROUND));
		screen.addVerifyListener(new VerifyListener() {
			
			@Override
			public void verifyText(VerifyEvent e) {
				char character = e.character;
				commandBuffer.append(character);
				System.out.println("------   " + character);
			}
		});
		screen.addKeyListener(new KeyListener() {
			
			@Override
			public void keyReleased(KeyEvent e) {
				System.out.println("keyReleased: "+e.keyCode);
				
			}
			@Override
			public void keyPressed(KeyEvent e) {
				System.out.println("keyPressed: "+e.keyCode);
				if(e.character == SWT.CR) {
					String string = commandBuffer.toString();
					sendCommand(string);
					System.out.println("发送命令。。。 " + string);
					commandBuffer.delete(0,commandBuffer.length());
				}
			}
		});
		
		commandInput = new Text(top, SWT.BORDER|SWT.WRAP);
		GridData commandLayoutData = new GridData(GridData.FILL,GridData.FILL,true,false);
		commandLayoutData.heightHint = commandInput.getLineHeight() * 2;
		commandInput.setLayoutData(commandLayoutData);
		TerminalEditor editor = this;
		commandInput.addKeyListener(new KeyListener() {
			
			@Override
			public void keyReleased(KeyEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void keyPressed(KeyEvent e) {
				if(e.character == SWT.CR) {
					System.out.println("CR:  "+e.character);
					sendCommand(commandInput.getText());
					commandInput.setText("");
					e.doit = false;
				}
			}
		});
	}
	
	/**
	 * AnsiControlSequenceParser解析完后,返回到下面的parsedString方法
	 * com.grahamedgecombe.jterminal.vt100.Vt100TerminalModel.Vt100Listener.parsedString(String)
	 * @param cc
	 */
	private void sendCommand(String cc) {
		try {
			char[] charArray = cc.toCharArray();
			for (char c : charArray) {
				System.out.println(c);
			}
			String command = cc+"\r";
//			String command = cc;
			try {
	            getOriginOutputStream().write(command.getBytes("UTF-8"));
	            getOriginOutputStream().flush();
	        } catch (SocketException var4) {
//	            this.displayTextInTerminal(var4.getMessage());
//	            String strMsg = TerminalMessages.SocketError + "!\n" + var4.getMessage();
//	            this.showErrorMessage(strMsg);
//	            this.disconnectTerminal();
	        } catch (IOException var5) {
//	            this.disconnectTerminal();
	        }
//			sshClient.sendCmd(command,editor);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void initPollingMsgJob() {
		if (this.readerJob == null) {
            this.readerJob = new Job("Terminal data reader") {
                protected IStatus run(IProgressMonitor monitor) {
                    IStatus var2 = Status.OK_STATUS;

                    Object status;
                    try {
                        while(true) {
                        	byte[] bytes = new byte[2048];
//            				System.out.println("pulling out");
            		        int n;
//                        	System.out.println("available... ...");
                        	try {
								
//								while ((n = originInputStream.read(bytes)) != -1) {
//									String outPut = new String(bytes, "UTF-8");
//									System.out.println("---------- " + outPut);
//									Display.getDefault().syncExec(new Runnable() {
//										public void run() {
//											appendOutPut(outPut);
//										}
//									});
//									bytes = new byte[2048];
//								}
								 
                        		while(hasNextChar()) {
                        			processText();
//                        			processTextSwing();
                        		}
							} catch (IOException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}

                            if (monitor.isCanceled()) {
                                status = Status.CANCEL_STATUS;
                                break;
                            }

//                            try {
//                            	TerminalEditor.this.processText();
//                            } catch (Exception e) {
//                            	sshClient.logout();
//                                status = new Status(4, "org.eclipse.tm.terminal.control", e.getLocalizedMessage(), e);
//                                break;
//                            }
                        }
                    } finally {
                        synchronized(TerminalEditor.this) {
                            if (TerminalEditor.this.readerJob == this) {
                            	TerminalEditor.this.readerJob = null;
                            }

                        }
                    }

                    return (IStatus)status;
                }
            };
            this.readerJob.setSystem(true);
            this.readerJob.schedule();
        }
	}

	public void startReaderJob() {
		this.inputStream = new PipedInputStream(8192);
		try {
			this.reader = new InputStreamReader(this.inputStream,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		
		
		if (this.readerJob == null) {
            this.readerJob = new Job("Terminal data reader") {
                protected IStatus run(IProgressMonitor monitor) {
                    IStatus var2 = Status.OK_STATUS;

                    Object status;
                    try {
                        while(true) {
                        	System.out.println("available... ...");
                            while(inputStream.available() == 0 && !monitor.isCanceled()) {
                                try {
                                	TerminalEditor.this.inputStream.waitForAvailable(500L);
                                } catch (InterruptedException var12) {
                                    Thread.currentThread().interrupt();
                                }
                            }

                            if (monitor.isCanceled()) {
                                status = Status.CANCEL_STATUS;
                                break;
                            }

                            try {
                            	TerminalEditor.this.processText();
                            } catch (Exception e) {
                            	sshClient.logout();
                                status = new Status(4, "org.eclipse.tm.terminal.control", e.getLocalizedMessage(), e);
                                break;
                            }
                        }
                    } finally {
                        synchronized(TerminalEditor.this) {
                            if (TerminalEditor.this.readerJob == this) {
                            	TerminalEditor.this.readerJob = null;
                            }

                        }
                    }

                    return (IStatus)status;
                }
            };
            this.readerJob.setSystem(true);
            this.readerJob.schedule();
        }
	}
	
	
	private int fNextChar = -1;
	private boolean hasNextChar() throws IOException {
        return this.fNextChar >= 0 ? true : this.reader.ready();
    }
	protected void processTextSwing() {
		try {
			
			while(hasNextChar()) {
				CharBuffer charArr = CharBuffer.allocate(1024);
				
				reader.read(charArr);
				
				String output = new String(charArr.array());
				Display.getDefault().syncExec(new Runnable() {
					public void run() {
						appendOutPut(output);
					}
				});
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	protected void processText() {
		try {
			CharBuffer charArr = CharBuffer.allocate(1024);
			CharBuffer ctrlCharArr = CharBuffer.allocate(1024);
			boolean isCtrlStart = false;
			boolean isCtrlEnding = false;
			int readIndex = 0;
			while(hasNextChar()) {
//				System.out.println("processText..........");
//				CharBuffer charArr = CharBuffer.allocate(1024);
//				reader.read(charArr);
//				String output = new String(charArr.array());
//				System.out.println(output);
				
//				Display.getDefault().syncExec(new Runnable() {
//					public void run() {
//						appendOutPut(output);
//					}
//				});
				
				char read = (char)reader.read();
				if(isCtrlEnding) {
					
					if(read == '[') {
						readIndex = ctrlCharArr.length()-1;
						ctrlCharArr.append(read);
					}
					if(read == 'm') {
						isCtrlStart = false;
						StringBuffer sb = new StringBuffer();
						for (int i = readIndex; i <= ctrlCharArr.length(); i++) {
							char c = ctrlCharArr.get(i);
							sb.append(c);
						}
						System.out.println(sb.toString());
					}
				}
				
				//控制字符开始了，又遇到了\033  ,表示马上就要结束了
				if(isCtrlStart && read == '\033') {
					isCtrlEnding = true;
					ctrlCharArr.append(read);
					System.out.println(new String(ctrlCharArr.array()));
					continue;
				}
				switch (read) {
				case '\033':
					if(!isCtrlStart) {
						isCtrlStart = true;
						System.out.println("VT100控制字符start... ");
					}else {
						System.out.println("VT100控制字符end... ");
						
					}
					ctrlCharArr.append(read);
					break;

				default:
					isCtrlStart = false;
					charArr.append(read);
					break;
				}
			}
			String output = new String(charArr.array());
			String output2 = new String(ctrlCharArr.array());
			System.out.println(output2);
			Display.getDefault().syncExec(new Runnable() {
			public void run() {
				appendOutPut(output);
			}
			});
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

	@Override
	public void setFocus() {
//		String text = commandInput.getText();
//		System.out.println(text);
//		commandInput.setText("");

	}
	
	public void appendOutPut(String str) {
//		this.screen.append(str);
//		this.shell.addMessageToDataScope(str);
//		Ascii.BEL
//		jterminal.print(str);
//		jterminal.repaint();
	}

	public void setISSHClient(ISSHClient sshClient) {
		this.sshClient = sshClient;
	}

	public InputStream getOriginInputStream() {
		return originInputStream;
	}

	/**
	 * 输入流字符读取设置
	 * @param inputStream
	 */
	public void setOriginInputStream(InputStream inputStream) {
		this.originInputStream = inputStream;
		this.reader = new InputStreamReader(inputStream);
	}

	public OutputStream getOriginOutputStream() {
		return originOutputStream;
	}

	public void setOriginOutputStream(OutputStream originOutputStream) {
		this.originOutputStream = originOutputStream;
	}

	public void setShell(MyVT100 shell) {
		this.shell = shell;
	}
	
	class RePaintTimer implements ActionListener{
		TerminalEditor ui;

		public RePaintTimer(TerminalEditor ui) {
			super();
			this.ui = ui;
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			System.out.println("redraw... shell");
//			Display current = Display.getDefault(); 和独立的main swt启动不同,这里要用PlatformUI获取显示对象
			Display display = PlatformUI.getWorkbench().getDisplay();
			if (display != null) {
				display.asyncExec(new Runnable() {
					
					@Override
					public void run() {
						if (!canvas.isDisposed()) {
							canvas.redraw();
						}
					}
				});
			}
		}
		
		
	}
}
